package com.itstyle.quartz.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

public class UrlParams {

	public static Map<String, String> getUrlParams(HttpServletRequest request) {
		Map<String, String[]> parameters = request.getParameterMap();
		Map<String, String> params = new HashMap<String, String>();
		if (parameters != null && parameters.size() > 0) {
			Iterator<String> iter = parameters.keySet().iterator();
			while (iter.hasNext()) {
				String key = iter.next();
				String[] values = parameters.get(key);
				for (int i = 0; i < values.length; i++) {
					String value = values[i];
					params.put(key, value);
				}
			}
		}
		return params;
	}

	public static String getUrlFromMap(HttpServletRequest request) {
		Map<String, String[]> params = request.getParameterMap();
		if (params == null) {
			return StringUtils.EMPTY;
		}

		StringBuffer sb = new StringBuffer();
		List<Entry<String, String[]>> paramList = new ArrayList<Map.Entry<String, String[]>>(params.entrySet());

		for (Entry<String, String[]> entry : paramList) {
			if (StringUtils.isNotBlank(entry.getKey())) {
				String[] values = entry.getValue();
				for (String value : values) {
					sb.append(entry.getKey()).append("=").append(value).append("&");
				}
			}
		}

		String url = sb.toString();
		if (url.endsWith("&")) {
			url = StringUtils.substringBeforeLast(url, "&");
		}

		return url;
	}

	/**
	 * @param request
	 */
	public static void setViewParams(HttpServletRequest request) {
		Map<String, String[]> params = request.getParameterMap();
		if (!CollectionUtils.isEmpty(params)) {
			List<Entry<String, String[]>> paramList = new ArrayList<Map.Entry<String, String[]>>(params.entrySet());

			for (Entry<String, String[]> entry : paramList) {
				String key = entry.getKey();
				if (StringUtils.isNotEmpty(key)) {
					String[] values = entry.getValue();
					if (values != null) {
						request.setAttribute(key, values);
					}
				}
			}
		}
	}

}
